function init(){
    if (!localStorage.contextSearch) {
        localStorage.searchUrl = "http://ws.spotify.com/search/1/track?q=";
		localStorage.searchType = chrome.i18n.getMessage("context_txt_search_artist");
        chrome.tabs.getSelected(null, function(tab){
            if (tab.url == "chrome://newtab/") {
                $("#message").show();
                $("#txtMessage").html(chrome.i18n.getMessage("popup_txt_no_selection"));
                $("#loading").hide();
            }
            else {
                var bg = chrome.extension.getBackgroundPage();
                bg.getPageInfo(onPageInfo);
            }
        });
    }
    else {
    
        var sel = localStorage.contextSearch.trim();
        if (sel.length > 0) {
            $("#txtSearching").html(chrome.i18n.getMessage("popup_txt_searching").format(sel,localStorage.searchType));
            searchTrack(sel);
        }
        else {
            $("#message").show();
            $("#txtMessage").html(chrome.i18n.getMessage("popup_txt_no_selection"));
            $("#loading").hide();
        }
		localStorage.remove('contextSearch');
    }
}


// This callback function is called when the content script has been 
// injected and returned its results
function onPageInfo(o){
    if (o.selectedText != "") {
        o.selectedText = o.selectedText.trim();
        if (o.selectedText.length > 0) {
            $("#txtSearching").html(chrome.i18n.getMessage("popup_txt_searching").format(o.selectedText));
            searchTrack(o.selectedText);
        }
        else {
            $("#message").show();
            $("#txtMessage").html(chrome.i18n.getMessage("popup_txt_no_selection"));
            $("#loading").hide();
        }
    }
    else {
        $("#message").show();
        $("#txtMessage").html(chrome.i18n.getMessage("popup_txt_no_selection"));
        $("#loading").hide();
    }
}


function createTab(strUrl){
    strUrl = strUrl.split(":").join("/");
    strUrl = strUrl.split("spotify").join("http://open.spotify.com");
    chrome.tabs.create({
        url: strUrl
    });
}


function searchTrack(strText){
    strText = strText.trim();
    if (strText.length > 0) {
        trackEvent("search", strText.toLowerCase());
        var strRowPattern = "<td><a href='#' onclick='createTab(\"{6}\");'>{0}</a></td><td><a href='#' onclick='createTab(\"{7}\");'>{1}</a></td><td><a href='#' onclick='createTab(\"{8}\");'>{2}</a></td><td>{3}</td><td>{4}</td><td><span style='display:none'>{5}</span><span title='{5}' class='starRating' value='{5}'></span> </td>";
        $.ajax({
            type: "GET",
            url: localStorage.searchUrl + encodeURIComponent(strText),
            contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
            dataType: "xml",
            error: function(request, error){
                $("#loading").hide();
                $("#message").show();
                $("#txtMessage").html(error + " " + request.responseText);
            },
            success: function(xml){
                var i = 0;
                $(xml).find('track').each(function(){
                    i++;
                    var track_name = "";
                    var track_url = "";
                    var artist = "";
                    var artist_url = "";
                    var album = "";
                    var album_url = "";
                    var released = "";
                    var track_length = "";
                    var track_popularity = "";
                    track_url = $(this).attr("href");
                    $(this).children().each(function(){
                        switch ($(this).get(0).tagName) {
                            case "name":
                                track_name = $(this).text();
                                break;
                            case "artist":
                                artist = $(this).get(0).childNodes(1).textContent;
                                artist = formatText(artist);
                                artist_url = $(this).attr("href");
                                break;
                            case "album":
                                album = $(this).get(0).childNodes(1).textContent;
                                released = $(this).get(0).childNodes(3).textContent;
                                album_url = $(this).attr("href");
                                break;
                            case "length":
                                var iNum = parseFloat($(this).text());
                                track_length = parseInt(iNum / 60) + ":" + pad(parseInt(iNum % 60), 2);
                                break;
                            case "popularity":
                                var iNum = parseFloat($(this).text()) * 100;
                                iNum = parseFloat(parseInt(iNum / 10) + "." + parseInt(iNum % 10));
                                iNum = (5 * iNum) / 10;
                                track_popularity = iNum;
                                break;
                        }
                    });
                    $('<tr></tr>').html(strRowPattern.format(track_name, artist, album, released, track_length, track_popularity, track_url, artist_url, album_url)).appendTo('#demoTable tbody');
                }); //close each(
                $('.starRating').each(function(index){
                    var iNum = parseFloat($(this).attr("value")) * 10;
                    var iNumEntero = parseInt(iNum / 10);
                    var iNumResto = parseInt(iNum % 10);
                    //$(this).text("-" + iNumEntero + "-" + iNumResto);
                    var iNumTotal = 0;
                    for (var i = 0; i < iNumEntero; i++) {
                        iNumTotal++;
                        $(this).append("<img src='../img/estrella-1.png' />");
                    }
                    if (iNumResto >= 5) {
                        $(this).append("<img src='../img/estrella-0.5.png' />");
                        iNumTotal++
                    }
                    
                    if (iNumTotal < 5) {
                        for (var i = 0; i < (5 - iNumTotal); i++) {
                            $(this).append("<img src='../img/estrella-0.png' />");
                        }
                    }
                });
                
                $("#loading").hide();
                
                $("#thName").text(chrome.i18n.getMessage("popup_txt_header_name"));
                $("#thArtist").text(chrome.i18n.getMessage("popup_txt_header_artist"));
                $("#thAlbum").text(chrome.i18n.getMessage("popup_txt_header_album"));
                $("#thReleased").text(chrome.i18n.getMessage("popup_txt_header_released"));
                $("#thLength").text(chrome.i18n.getMessage("popup_txt_header_length"));
                $("#thPopularity").text(chrome.i18n.getMessage("popup_txt_header_popularity"));
                $(".paginationTitle").text(chrome.i18n.getMessage("popup_txt_header_pagination_title"));
                
                $('.tabla-wrapper').show();
                
                
                if (i > 0) {
                    $('.cabecera').html("<i>" + localStorage.searchType + "</i>:&nbsp;&nbsp;<b>" + strText + "</b>");
                    $('#demoTable').jTPS({
                        perPages: [10, 25, 50, 'ALL'],
                        scrollStep: 1,
                        scrollDelay: 30,
                        clickCallback: function(){
                        }
                    });
                    
                    
                    // reinstate sort and pagination if cookie exists
                    var cookies = document.cookie.split(';');
                    for (var ci = 0, cie = cookies.length; ci < cie; ci++) {
                        var cookie = cookies[ci].split('=');
                        if (cookie[0] == 'jTPS') {
                            var commands = cookie[1].split(',');
                            for (var cm = 0, cme = commands.length; cm < cme; cm++) {
                                var command = commands[cm].split(':');
                                if (command[0] == 'sortasc' && parseInt(command[1]) >= 0) {
                                    $('#demoTable .sortableHeader:eq(' + parseInt(command[1]) + ')').click();
                                }
                                else 
                                    if (command[0] == 'sortdesc' && parseInt(command[1]) >= 0) {
                                        $('#demoTable .sortableHeader:eq(' + parseInt(command[1]) + ')').click().click();
                                    }
                                    else 
                                        if (command[0] == 'page' && parseInt(command[1]) >= 0) {
                                            $('#demoTable .pageSelector:eq(' + parseInt(command[1]) + ')').click();
                                        }
                            }
                        }
                    }
                    
                    // bind mouseover for each tbody row and change cell (td) hover style
                    $('#demoTable tbody tr:not(.stubCell)').bind('mouseover mouseout', function(e){
                        // hilight the row
                        e.type == 'mouseover' ? $(this).children('td').addClass('hilightRow') : $(this).children('td').removeClass('hilightRow');
                    });
                }
                else {
                    $("#txtMessage").html("<div class='buscar'>" + chrome.i18n.getMessage("popup_txt_not_found_1").format(strText) + "<br /><br />" + chrome.i18n.getMessage("popup_txt_not_found_2") + "<br /><br /><input type='text' id='txtArtist'><img src='../img/ico-lupa.png' id='btnSearch' alt='buscar'></div> ");
                    $("#message").show();
                    $(".tabla-wrapper").hide();
                    $(document).ready(function(){
                        console.log("set focus");
                        $("#txtArtist").focus();
                        $('#txtArtist').keyup(function(e){
                            if (e.keyCode == 13) {
                                newSearch();
                            }
                        });
                        $('#btnSearch').click(function(e){
                            newSearch();
                        });
                    });
                }
                
            }
        }); //close $.ajax(	
    }
}

function newSearch(){
    var strText = '';
    strText = $('#txtArtist').val().trim();
    if (strText.length > 0) {
        $("#message").hide();
        $("#txtSearching").html(chrome.i18n.getMessage("popup_txt_searching").format($('#txtArtist').val(),localStorage.searchType));
        $("#loading").show();
        searchTrack($('#txtArtist').val());
    }
}

function pad(number, length){
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

function formatText(strText){
    if (strText.trim().length > 40) 
        return Mid(strText, 0, 39) + "...";
    else 
        return strText;
}

function Mid(str, start, len){
    // Make sure start and len are within proper bounds
    if (start < 0 || len < 0) 
        return "";
    var iEnd, iLen = String(str).length;
    if (start + len > iLen) 
        iEnd = iLen;
    else 
        iEnd = start + len;
    return String(str).substring(start, iEnd);
}



